package com.company.common.core.util;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Date;

public class PoiUtils {

	public static String getPOICellvalue(Cell cell) {
		return getPOICellvalue(cell, "yyyy-MM-dd");
	}

	/**
	 * 读取每个单元格之内的数据，转换成字符串形式
	 * 
	 * @param cell
	 * @return
	 */
	public static String getPOICellvalue(Cell cell, String dateFormat) {
		String value = null;
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:
			CellStyle style = cell.getCellStyle();
			if (style != null && style.getDataFormat() > 0) {
				String formatstr = style.getDataFormatString();
				if (formatstr != null && (DateUtil.isCellDateFormatted(cell) || (formatstr.contains("年")))) {
					Date dt = cell.getDateCellValue();
					value = DateFormatUtils.format(dt, dateFormat);
					break;
				}
			}
			Double db = cell.getNumericCellValue();
			long dbl = 0;
			if ((db % 1.0d) == 0) {
				dbl = db.longValue();
				value = String.valueOf(dbl);
			} else {
				// 目前先最多保留五位
				DecimalFormat df = new DecimalFormat("#.#####");
				df.setRoundingMode(RoundingMode.HALF_UP);
				value = df.format(db);
			}
			break;

		case HSSFCell.CELL_TYPE_STRING:
			value = cell.getStringCellValue();
			break;

		case HSSFCell.CELL_TYPE_BLANK:
			value = "";
			break;

		case HSSFCell.CELL_TYPE_FORMULA:
			value = cell.getCellFormula();
			break;

		case HSSFCell.CELL_TYPE_BOOLEAN:
			value = String.valueOf(cell.getBooleanCellValue());
			break;

		case HSSFCell.CELL_TYPE_ERROR:
			value = "error";
			break;

		default:
			break;
		}

		return value;
	}

}
